#include "chartwidget.h"

ChartWidget::ChartWidget(QString table,
                         QString num,
                         QString name,
                         QString filter,
                         QMap<int,int> asc_indicies,
                         QMap<int,int> desc_indicies)
{
this->setAttribute(Qt::WA_DeleteOnClose);
setupUi(this);
filter_ = filter;

Schema * schema = new Schema;
    if (NULL == schema)
    {
    return;
    }

QList<int> il;
il << 1   // "denomination"
   << 2   // "obj_year"
   << 3   // "marks"
   << 4   // "rating"
   << 5   // "state"
   << 6   // "epoch"
   << 7   // "edge"
   << 8   // "material"
   << 10  // "condition"
   << 11  // "certified"
   << 12  // "cert_auth"
   << 18  // "axis1"
   << 19  // "axis2"
   << 20  // "shape"
   << 23  // "edgeid"
   << 25  // "obj_type"
   << 26  // "obj_undertype"
   << 28  // "obverseartist"
   << 29  // "reverseartist"
   << 30  // "obverseengraver"
   << 31  // "reverseengraver"
   << 32  // "issuer"
   << 33  // "authority"
   << 34  // "mint"
   << 36  // "mintage"
   << 37  // "obversesymbol"
   << 38  // "obversetype"
   << 41  // "obversedieid"
   << 42  // "obversecountermark"
   << 43  // "reversesymbol"
   << 44  // "reversetype"
   << 47  // "reversedieid"
   << 48  // "reversecountermark"
   << 49  // "fromdate"
   << 50  // "todate"
   << 51  // "dateonobject"
   << 52  // "eraonobject"
   << 53  // "ruleronobject"
   << 54  // "region"
   << 55  // "findspot"
   << 59  // "status"
   << 61  // "location"
   << 62  // "seller"
   << 68  // "customer"
   << 69  // "owner"
   << 70  // "title"
   << 72  // "collection"
   << 73  // "collectionid"
   << 74  // "projectid"
   << 75  // "hoard"
   << 76  // "catalogid"
   << 79  // "recordtype"
   << 80  // "reserved_1"
   << 81  // "reserved_2"
   << 82  // "reserved_3"
   << 83  // "reserved_4"
   << 84  // "reserved_5"
   << 85  // "reserved_6"
   << 86  // "reserved_7"
   << 87  // "reserved_8"
   << 88  // "reserved_9"
   << 89  // "reserved_10"
   << 90  // "reserved_11"
   << 91  // "reserved_12"
   << 92  // "reserved_13"
   << 93  // "reserved_14"
   << 94  // "reserved_15"
   << 95;  // "reserved_16"

QMap<QString, int> columns_map = schema->columns_map();
QMap<int, QString> headers = schema->headers();
QMap<int, QString> column_names = schema->column_names();

    for (int i = 0; i < il.size(); ++i)
    {
        if ( asc_indicies.value( il.at(i) ) == 1 &&
             desc_indicies.value( il.at(i) ) == 1 )
        {
        comboBox->addItem( QIcon( QPixmap(":/binary/indexed.png") ),
                           headers.value( il.at(i) ),
                           QVariant() );
        l << column_names.value( il.at(i) );
        }
        else
        {
        comboBox->addItem( QIcon( QPixmap(":/binary/empty-16.png") ),
                           headers.value( il.at(i) ),
                           QVariant() );
        l << column_names.value( il.at(i) );
        }
    }
comboBox->setCurrentIndex(-1);

QString album_label = QLatin1String("<b>");
album_label.append(num);
album_label.append( QLatin1String(" ") );
album_label.append(name);
album_label.append( QLatin1String("</b>") );
album = table;
albumNameLabel->setText(album_label);
setup_model();
setup_view();

connect( comboBox,
         SIGNAL( activated(int) ),
         this,
         SLOT( new_query(int) ) );
}

ChartWidget::~ChartWidget()
{
}

void ChartWidget::get_data(const QString column)
{
m.clear();

QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( !db.isOpen() )
    {
    QMessageBox::warning(this,
                         tr("Error"),
                         tr("Database is closed.") );
    return;
    }

    if ( album.isEmpty() )
    {
    return;
    }

    if ( column.isEmpty() )
    {
    return;
    }

QString s = QLatin1String("select ");
s.append(column);
s.append(QLatin1String(",count(1) from ") );
s.append(album);

    if ( true != filter_.isEmpty() )
    {
    s.append( QLatin1String(" where ") );
    s.append(filter_);
    }

s.append( QLatin1String(" group by ") );
s.append(column);
QSqlQuery query(s, db);
    while (query.next())
    {
    QString k = query.value(0).toString();
    double v = query.value(1).toDouble();
    m[k] = v;
    }
query.clear();
}

void ChartWidget::populate_model()
{
model->removeRows(0, model->rowCount(QModelIndex()), QModelIndex());
QMapIterator<QString, double> i(m);
int row = 0;
    while (i.hasNext())
    {
    i.next();

    QVariant k_;
        if ( i.key().isNull() || i.key().isEmpty() )
        {
        k_ = QVariant( QString("NULL") );
        }
        else
        {
        k_ = QVariant( QString( i.key() ) );
        }
    QVariant i_ = QVariant( i.value() );
    QColor color = generate_color(row);
    model->insertRows(row, 1, QModelIndex());
    model->setData( model->index( row, 0, QModelIndex() ),
                    k_ );
    model->setData( model->index( row, 1, QModelIndex() ),
                    i_ );
    model->setData(model->index(row, 0, QModelIndex()),
                   color,
                   Qt::DecorationRole );
    row++;
    }
m.clear();
}

QColor ChartWidget::generate_color(int row)
{
int hue = 60*row;
int saturation = 250;
int value = 250;
    if ( row >= 6)
    {
       if ( true != (359 >= hue + 30) )
       {
       hue = hue + 30;
       }
       else
       {
       hue = hue - 30;
       }
    
       if ( true != (0 >= saturation - 10) )
       {
       saturation = saturation - 10;
       }
    value = 186;
    }
    if ( row >= 120)
    {
       if ( true != (359 >= hue + 30) )
       {
       hue = hue + 30;
       }
       if ( true != (0 >= saturation - 10) )
       {
       saturation = saturation - 10;
       }
    value = 128;
    }
QColor color;
color.setHsv(hue, saturation, value);
return color;
}

void ChartWidget::setup_model()
{
model = new QStandardItemModel(m.size(), 2, this);
model->setHeaderData(0, Qt::Horizontal, tr("Columns"));
model->setHeaderData(1, Qt::Horizontal, tr("Quantities"));
}

void ChartWidget::setup_view()
{
QSplitter * splitter = new QSplitter;

QTableView * chartTableView = new QTableView();
chartTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
chartTableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
chartTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
chartTableView->setSortingEnabled(true);
chartTableView->setModel(model);

pieChart = new PieView();
pieChart->setEditTriggers(QAbstractItemView::NoEditTriggers);
pieChart->setModel(model);

splitter->addWidget(chartTableView);
splitter->addWidget(pieChart);
splitter->setStretchFactor(0, 0);
splitter->setStretchFactor(1, 1);

QItemSelectionModel * selectionModel = new QItemSelectionModel(model);
chartTableView->setSelectionModel(selectionModel);
pieChart->setSelectionModel(selectionModel);

QHBoxLayout * hLayout = new QHBoxLayout(centralWidget);
hLayout->setSpacing(6);
hLayout->setMargin(0);

hLayout->addWidget(splitter);
}

void ChartWidget::new_query(int i)
{
const QString c = l.at(i);
    if ( c.isEmpty() )
    {
    return;
    }
get_data(c);
populate_model();
}

